package com.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import vo.User;

public class UserLoginDaoImpl extends BaseDao implements UserLoginDao {

	@Override
	public User selectUserByUsernameAndPassword(String username, String password) {
		User user=null;
		Connection conn=null;
		PreparedStatement ps=null;
		 ResultSet rs=null;
		try {
			conn=this.getConnection();
			ps=conn.prepareStatement("select * from tb_user where name=? and password=?");
			ps.setString(1, username);
			ps.setString(2, password);
			rs=ps.executeQuery();
			while(rs.next()) {
				user=new User();
				user.setUserid(rs.getInt("userid"));
				user.setUsername(rs.getString("name"));
				user.setPassword(rs.getString("password"));
				user.setRealname(rs.getString("realname"));
			}
			
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			this.close(rs);
			this.close(ps);
			this.close(conn);
		}
		return user;
	}
	
	//将List<Map<String,Object>>转换成List<User>
		private List<User> convert(List<Map<String,Object>> list){
			List<User> blist=new ArrayList<User>();
			for(Map<String,Object> map:list) {
				User b=new User();
				b.setUserid((Integer)map.get("userid"));
				b.setUsername(map.get("name").toString());
				b.setPassword(map.get("password").toString());
				b.setRealname(map.get("realname").toString());
				blist.add(b);
			}

			
			return blist;
		}

	@Override
	public List<User> getAll() {
		
		return this.convert(this.executeQuery("select * from tb_user order by userid"));
	}

}
